<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>保持页面比例</title>
    <link rel="shortcut icon" href="../lib/image/favicon.ico" type="image/x-icon">
    <!-- 该页面 all.css 可不必使用 -->
    <link rel="stylesheet" href="../lib/css/all.css">

</head>
<style>
    html,
    body {
        margin: 0;
        padding: 0;
        overflow: hidden;
    }
    
    #app {
        width: 100vw;
        height: 100vh;
        overflow: hidden;
    }
    
    .box {
        color: #d3d6dd;
        width: 1920px;
        height: 1080px;
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
        -webkit-transform-origin: left top;
        transform-origin: left top;
        overflow: hidden;
        font-size: 23px;
        background-image: url(../lib/image/1.jpg);
    }
</style>

<body>
    <div id="app">
        <div class="box">
            浏览器放大与缩小时，尽量保持所展示内容不变。 1920*1080
        </div>
    </div>
    <script>
        // * 默认缩放值
        const scale = {
            width: '1',
            height: '1',
        }

        // * 设计稿尺寸（px）
        const baseWidth = 1920
        const baseHeight = 1080

        // * 需保持的比例（默认1.77778）
        const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))

        function calcRate() {
            const appRef = document.querySelector('.box');
            if (!appRef) return
                // 当前宽高比
            const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
            if (appRef) {
                if (currentRate > baseProportion) {
                    // 表示更宽
                    scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
                    scale.height = (window.innerHeight / baseHeight).toFixed(5)
                    appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
                } else {
                    // 表示更高
                    scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5)
                    scale.width = (window.innerWidth / baseWidth).toFixed(5)
                    appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
                }
            }
        }

        calcRate()

        // 监听窗口变化重载
        window.addEventListener('resize', function() {
            calcRate()
        })
    </script>
</body>

</html>